const jwt = require('jsonwebtoken')
const { secretKey } = require('../constants/const.js')
const { UN_LOGIN } = require('../constants/HttpCode')
const ResponseUtil = require('../utils/Response')

module.exports = () => {
  return async function auth(ctx, next) {
    const { token } = ctx.event
    if (!token) {
      return ResponseUtil.error('用户未登录', 401)
    }
    try {
      const decoded = jwt.verify(token, secretKey)
      ctx.openId = decoded.openId
      await next()
    }
    catch (err) {
      if (err.name === 'TokenExpiredError') {
        return ctx.body = ResponseUtil.error('登录状态已过期', 401)
      }
	  console.log("err",err)
      ctx.body = ResponseUtil.error(err.errMsg || '接口异常')
    }
  }
}
